<?php
session_start();
require_once 'common/auth.php';
require_once 'database.php';

// 启用错误显示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 检查登录状态
if (!checkLogin()) {
    header('Location: index.php');
    exit;
}

// 获取用户角色
$user_roles = getUserRoles($_SESSION['user_id']);
if (!in_array('考试项目管理员', $user_roles)) {
    header('Location: access_denied.php');
    exit;
}

// 获取考试项目ID
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
if ($exam_id === 0) {
    echo "无效的考试项目ID";
    exit;
}

// 获取考试项目信息
$exam_info = null;
try {
    $stmt = $pdo->prepare("SELECT exam_name FROM exams WHERE id = ?");
    $stmt->execute([$exam_id]);
    $exam_info = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$exam_info) {
        echo "考试项目不存在";
        exit;
    }
} catch (PDOException $e) {
    echo "数据库查询失败: " . $e->getMessage();
    exit;
}

// 获取考试场次数据
$sessions_data = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number");
    $stmt->execute([$exam_id]);
    $sessions_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "获取考试场次数据失败: " . $e->getMessage();
}

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    
    if ($action === 'generate_invigilators') {
        try {
            // 计算考试项目需要监考员总数（含备用考场）
            $max_invigilators_needed = 0;
            $backup_rooms_count = 0;
            
            foreach ($sessions_data as $session) {
                $session_invigilators = intval($session['session_rooms_needed']) * intval($session['invigilators_per_room']);
                $max_invigilators_needed = max($max_invigilators_needed, $session_invigilators);
                $backup_rooms_count = max($backup_rooms_count, intval($session['backup_rooms_count']));
            }
            
            $total_invigilators_needed = $max_invigilators_needed + ($backup_rooms_count * 2);
            
            // 生成监考员列表
            $invigilators_list = [];
            for ($i = 1; $i <= $total_invigilators_needed; $i++) {
                $invigilators_list[] = "监考员{$i}";
            }
            
            echo json_encode([
                'success' => true,
                'total_invigilators_needed' => $total_invigilators_needed,
                'invigilators_list' => $invigilators_list
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
        exit;
    }
    
    if ($action === 'complete_arrangement') {
        try {
            $invigilators_list = isset($_POST['invigilators_list']) ? json_decode($_POST['invigilators_list'], true) : [];
            
            if (empty($invigilators_list)) {
                echo json_encode([
                    'success' => false,
                    'error' => '监考员列表为空'
                ]);
                exit;
            }
            
            // 为每个场次分配监考员
            foreach ($sessions_data as $session) {
                $session_invigilators_needed = intval($session['session_rooms_needed']) * intval($session['invigilators_per_room']);
                $session_invigilators = array_slice($invigilators_list, 0, $session_invigilators_needed);
                
                // 如果有备用考场，添加备用监考员
                if (intval($session['backup_rooms_count']) > 0) {
                    $backup_invigilators = array_slice($invigilators_list, $session_invigilators_needed, 2);
                    $session_invigilators = array_merge($session_invigilators, $backup_invigilators);
                }
                
                // 更新数据库
                $stmt = $pdo->prepare("
                    UPDATE arrange_examination_rooms_and_invigilators 
                    SET invigilators_list = ? 
                    WHERE id = ?
                ");
                $stmt->execute([json_encode($session_invigilators), $session['id']]);
            }
            
            // 更新考试项目进度
            $stmt = $pdo->prepare("UPDATE exams SET progress = 2 WHERE id = ?");
            $stmt->execute([$exam_id]);
            
            echo json_encode([
                'success' => true,
                'message' => '编排考场及预编排监考员完成！'
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编排考场及预编排监考员 - 里程碑5</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .milestone-nav {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 2rem;
        }
        .milestone-step {
            display: inline-block;
            padding: 0.5rem 1rem;
            margin: 0.25rem;
            border-radius: 20px;
            background: rgba(255,255,255,0.2);
            text-decoration: none;
            color: white;
            transition: all 0.3s ease;
        }
        .milestone-step.active {
            background: rgba(255,255,255,0.8);
            color: #333;
            font-weight: bold;
        }
        .milestone-step:hover {
            background: rgba(255,255,255,0.4);
            color: white;
        }
        .session-card {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: #f8f9fa;
        }
        .invigilator-item {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            margin: 0.25rem;
            background: #e3f2fd;
            border: 1px solid #2196f3;
            border-radius: 15px;
            font-size: 0.9rem;
        }
        .btn-generate {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 25px;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        .btn-generate:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            color: white;
        }
        .btn-complete {
            background: linear-gradient(135deg, #FF6B6B 0%, #ee5a52 100%);
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 25px;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        .btn-complete:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            color: white;
        }
        .result-section {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-top: 1rem;
        }
        .total-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <?php include_once 'common/navigation.php'; ?>
    
    <div class="container mt-4">
        <!-- 页面标题 -->
        <div class="row">
            <div class="col-12">
                <h2 class="mb-4">编排考场及预编排监考员</h2>
                <h4 class="text-primary mb-3">考试项目：<?php echo htmlspecialchars($exam_info['exam_name']); ?></h4>
            </div>
        </div>
        
        <!-- 里程碑导航 -->
        <div class="milestone-nav">
            <h5 class="mb-3">进度导航</h5>
            <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>" class="milestone-step">里程碑1: 填写考场数据</a>
            <a href="arrange_examination_rooms_milestone2.php?exam_id=<?php echo $exam_id; ?>" class="milestone-step">里程碑2: 计算重要数据</a>
            <a href="arrange_examination_rooms_milestone3.php?exam_id=<?php echo $exam_id; ?>" class="milestone-step">里程碑3: 遴选课室</a>
            <a href="arrange_examination_rooms_milestone4.php?exam_id=<?php echo $exam_id; ?>" class="milestone-step">里程碑4: 编排考场号</a>
            <a href="arrange_examination_rooms_milestone5.php?exam_id=<?php echo $exam_id; ?>" class="milestone-step active">里程碑5: 预编排监考员</a>
        </div>
        
        <?php if (!empty($sessions_data)): ?>
            <!-- 当前考试场次数据展示 -->
            <div class="row">
                <div class="col-12">
                    <h5 class="mb-3">当前考试场次数据</h5>
                    <?php foreach ($sessions_data as $session): ?>
                        <div class="session-card">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>第<?php echo $session['session_number']; ?>场次 - <?php echo htmlspecialchars($session['subject_name']); ?></h6>
                                    <p class="mb-1"><strong>考试时间：</strong><?php echo $session['exam_date']; ?> <?php echo $session['start_time']; ?> - <?php echo $session['end_time']; ?></p>
                                    <p class="mb-1"><strong>考场类型：</strong><?php echo $session['room_type']; ?></p>
                                    <p class="mb-1"><strong>所需考场数：</strong><?php echo $session['session_rooms_needed']; ?>个（不含备用）</p>
                                </div>
                                <div class="col-md-6">
                                    <p class="mb-1"><strong>每考场考生数：</strong><?php echo $session['students_per_room']; ?>人</p>
                                    <p class="mb-1"><strong>每考场监考员数：</strong><?php echo $session['invigilators_per_room']; ?>人</p>
                                    <p class="mb-1"><strong>备用考场数：</strong><?php echo $session['backup_rooms_count']; ?>个</p>
                                    <p class="mb-1"><strong>考场号编号规律：</strong><?php echo $session['room_number_pattern']; ?></p>
                                </div>
                            </div>
                            
                            <!-- 显示已分配的监考员（如果有） -->
                            <?php if (!empty($session['invigilators_list'])): ?>
                                <div class="mt-3">
                                    <strong>已分配监考员：</strong>
                                    <div class="mt-2">
                                        <?php 
                                        $assigned_invigilators = json_decode($session['invigilators_list'], true);
                                        if ($assigned_invigilators) {
                                            foreach ($assigned_invigilators as $invigilator) {
                                                echo '<span class="invigilator-item">' . htmlspecialchars($invigilator) . '</span>';
                                            }
                                        }
                                        ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- 预编排监考员操作 -->
            <div class="row mt-4">
                <div class="col-12 text-center">
                    <button type="button" class="btn btn-generate me-3" onclick="generateInvigilators()">
                        🎯 预编排监考员
                    </button>
                </div>
            </div>
            
            <!-- 监考员预编排结果 -->
            <div id="invigilator-result" class="result-section" style="display: none;">
                <h5 class="mb-3">监考员预编排结果</h5>
                
                <!-- 总体信息 -->
                <div id="total-info" class="total-info">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>考试项目需要监考员总数（含备用考场）</h6>
                            <h4 id="total-invigilators-count">--</h4>
                        </div>
                        <div class="col-md-6">
                            <h6>生成的监考员列表</h6>
                            <p>按递增顺序排列</p>
                        </div>
                    </div>
                </div>
                
                <!-- 监考员列表展示 -->
                <div id="invigilators-display" class="mt-3">
                    <h6>本场次监考员的姓名列表（含备用考场）：</h6>
                    <div id="invigilators-list" class="mt-2">
                        <!-- 监考员列表将在这里动态显示 -->
                    </div>
                </div>
                
                <!-- 完成编排按钮 -->
                <div class="text-center mt-4">
                    <button type="button" class="btn btn-complete" onclick="completeArrangement()">
                        ✅ 编排考场及预编排监考员
                    </button>
                    <p class="text-muted mt-2">点击后将完成所有编排工作并返回考试项目列表</p>
                </div>
            </div>
            
        <?php else: ?>
            <div class="alert alert-warning">
                <h5>⚠️ 暂无考试场次数据</h5>
                <p>请先完成前面的里程碑步骤。</p>
                <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">返回里程碑1</a>
            </div>
        <?php endif; ?>
        
        <!-- 导航按钮 -->
        <div class="row mt-5">
            <div class="col-6">
                <a href="arrange_examination_rooms_milestone4.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-secondary">
                    ← 上一步：里程碑4
                </a>
            </div>
            <div class="col-6 text-end">
                <a href="exam_projects.php" class="btn btn-outline-primary">
                    返回考试项目列表
                </a>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentInvigilatorsList = [];
        
        // 预编排监考员
        function generateInvigilators() {
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=generate_invigilators'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    currentInvigilatorsList = data.invigilators_list;
                    
                    // 显示结果区域
                    document.getElementById('invigilator-result').style.display = 'block';
                    
                    // 更新总监考员数量
                    document.getElementById('total-invigilators-count').textContent = data.total_invigilators_needed + ' 人';
                    
                    // 显示监考员列表
                    displayInvigilatorsList(data.invigilators_list);
                    
                    // 滚动到结果区域
                    document.getElementById('invigilator-result').scrollIntoView({ behavior: 'smooth' });
                } else {
                    alert('生成监考员列表失败：' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                alert('生成监考员列表失败，请重试');
            });
        }
        
        // 显示监考员列表
        function displayInvigilatorsList(invigilators) {
            const container = document.getElementById('invigilators-list');
            container.innerHTML = '';
            
            invigilators.forEach(invigilator => {
                const span = document.createElement('span');
                span.className = 'invigilator-item';
                span.textContent = invigilator;
                container.appendChild(span);
            });
        }
        
        // 完成编排
        function completeArrangement() {
            if (currentInvigilatorsList.length === 0) {
                alert('请先生成监考员列表！');
                return;
            }
            
            if (!confirm('确认完成编排考场及预编排监考员？\n完成后将更新项目进度并返回考试项目列表。')) {
                return;
            }
            
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=complete_arrangement&invigilators_list=' + encodeURIComponent(JSON.stringify(currentInvigilatorsList))
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    window.location.href = 'exam_projects.php';
                } else {
                    alert('完成编排失败：' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                alert('完成编排失败，请重试');
            });
        }
    </script>
</body>
</html>